package com.leyou.user.controller;

import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author syf
 * @version 1.0
 * @date 2019/08/11 21:36
 * @Description TODO:数据验证及注册控制器
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    //数据验证
    @GetMapping("/check/{data}/{type}")//data:要验证的数据 ；type:要校验的数据类型：1，用户名；2，手机
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data") String data,@PathVariable(value = "type") Integer type){
        return ResponseEntity.ok(userService.checkUserData(data,type));
    }

    //发送短信
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    //用户注册
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user,
                                         BindingResult result,
                                         @RequestParam("code") String code,
                                         @RequestParam("confirmPassword") String confirmPassword){
        if (result.hasErrors()) {
            String collect = result.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("/"));
            throw new LyException(400, collect);
        }
            userService.register(user,code,confirmPassword);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    //根据用户名和密码查询用户
    @GetMapping("/query")
    public ResponseEntity<UserDTO>  findByUsernameAndPassword(@RequestParam("username") String username,
                                                              @RequestParam("password") String password){
        return ResponseEntity.ok(userService.findByUsernameAndPassword(username,password));
    }


}
